package utils;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class FileUploadUtils {
    private final static String UPLOAD_PATH = "/upload";

    public static Map<String, Object> parse(HttpServletRequest req) {
        if (!ServletFileUpload.isMultipartContent(req)) {
            return null;
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletContext servletContext = req.getServletContext();
        File repository = (File)servletContext.getAttribute("javax.servlet.context.tempdir");

        factory.setRepository(repository);

        ServletFileUpload fileUpload = new ServletFileUpload(factory);

        HashMap<String, Object> result = new HashMap<>();

        try {
            List<FileItem> items = fileUpload.parseRequest(req);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    processFormFiled(item, result);
                } else {
                    processFile(item, result, servletContext);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static void processFile(FileItem item, HashMap<String, Object> result, ServletContext servletContext) throws Exception {
        String fieldName = item.getFieldName();
        String fileName = item.getName();

        String uuid = UUID.randomUUID().toString();
        fileName = uuid + "-" + fileName;

        String hexHash = Integer.toHexString(fileName.hashCode());
        char[] chars = hexHash.toCharArray();
        StringBuilder path = new StringBuilder(UPLOAD_PATH);
        for (char c : chars) {
            path.append("/").append(c);
        }
        path.append("/").append(fileName);

        String realPath = servletContext.getRealPath(path.toString());
        File file = new File(realPath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        item.write(file);
        result.put(fieldName, path.toString());
    }

    private static void processFormFiled(FileItem item, HashMap<String, Object> result) throws UnsupportedEncodingException {
        String fieldName = item.getFieldName();
        if (null == result.get(fieldName)) {
            result.put(fieldName, item.getString(StandardCharsets.UTF_8.toString()));
            return;
        }
        result.put(fieldName, result.get(fieldName) + "," + item.getString(StandardCharsets.UTF_8.toString()));
    }

}
